﻿namespace CookieTerm
{
    using System;
    using Gtk;

    public partial class MainWindow : Gtk.Window
    {
        BookmarkManager bookmarkManager;
        Menu contextMenu;

        Console ActiveConsole
        {
            get
            {
                return this.notebook.GetNthPage(this.notebook.CurrentPage) as Console;
            }
        }

        public MainWindow()
            : base(Gtk.WindowType.Toplevel)
        {
            Build();

            this.notebook.FocusGrabbed += OnNotebookFocusGrabbed;
            this.notebook.SwitchPage += OnStatusBarTextChanged;
            this.notebook.PageRemoved += OnStatusBarTextChanged;

            this.bookmarkManager = new BookmarkManager();
            this.bookmarkManager.Load();

            LoadBookmarkMenu();
            foreach (MenuItem child in mainMenuBar.AllChildren)
            {
                if (child.Name == "EditMenu")
                {
                    this.contextMenu = (Menu) child.Submenu;
                    break;
                }
            }
        }

		public void OnStatusBarTextChanged(object sender, EventArgs args)
		{
            this.statusBar.Push(0, ActiveConsole == null ? string.Empty : ActiveConsole.StatusText);
		}

        void OnNotebookFocusGrabbed(object sender, EventArgs e)
        {
            Console activeConsole = ActiveConsole;
            if (activeConsole != null)
            {
                activeConsole.GrabFocus();
            }
        }

        public void PopupContextMenu()
        {
            if (this.contextMenu != null)
            {
                this.contextMenu.Popup();
            }
        }

        void OnDeleteEvent(object sender, DeleteEventArgs a)
        {
            bool quit = true;
            for (int i = 0; i < this.notebook.NPages; i++)
            {
                Console console = (Console)this.notebook.GetNthPage(i);
                string message;
                bool okayToClose = console.Controller.RequestToShutdown(out message);

                if (!okayToClose)
                {
                    MessageDialog dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, message);
                    ResponseType response = (ResponseType)dialog.Run();
                    dialog.Destroy();
                    okayToClose = ResponseType.Yes == response;
                }

                quit &= okayToClose;

                if (!quit)
                {
                    break;
                }
            }

            if (quit)
            {
                Application.Quit();
            }

            a.RetVal = true;
        }

        void LoadBookmarkMenu()
        {
            MenuItem openMenuItem = (MenuItem)this.UIManager.GetWidget("/mainMenuBar/BookmarkMenu/OpenAction");
            if (openMenuItem == null)
            {
                throw new InvalidOperationException("Cannot find Bookmark -> Edit menu item.");
            }

            Menu openSubMenu = new Menu();
            openMenuItem.Submenu = openSubMenu;

            for (int i = 0; i < this.bookmarkManager.Bookmarks.Count; i++)
            {
                string text = (i < 10 ? "_" : "") + i + " " + this.bookmarkManager.Bookmarks[i].Name;
                MenuItem item = new MenuItem(text);
                item.Name = this.bookmarkManager.Bookmarks[i].Name;
                item.Activated += this.OnBookmarkClicked;

#if false
				if (i < 10) 
				{
					item.ShortcutKeys = Keys.Control | Keys.Alt | (Keys.D0 + i);
				}
				item.Click += new EventHandler (BookmarkClick);
#endif
                openSubMenu.Append(item);
            }

            ShowAll();
        }

        void OnManageMenuItemClicked(object sender, EventArgs e)
        {
        }

        protected override bool OnPopupMenu()
        {
            PopupContextMenu();
            return true;
        }

        protected override bool OnButtonPressEvent(Gdk.EventButton evnt)
        {
            if (evnt.Button == 3)
            {
                PopupContextMenu();
            }
            return base.OnButtonPressEvent(evnt);
        }

        void OnBookmarkClicked(object sender, EventArgs e)
        {
            MenuItem item = (MenuItem)sender;
            Bookmark bookmark = this.bookmarkManager.FindBookmark(item.Name);
            new Tab(bookmark, this.notebook);
        }

        protected void OnCopy(object sender, EventArgs e)
        {
            Console activeConsole = ActiveConsole;
            if (activeConsole != null)
            {
                activeConsole.Copy();
            }
        }

        protected void OnPaste(object sender, EventArgs e)
        {
            Console activeConsole = ActiveConsole;
            if (activeConsole != null)
            {
                activeConsole.Paste();
            }
        }

        protected void OnSelectAll(object sender, EventArgs e)
        {
            Console activeConsole = ActiveConsole;
            if (activeConsole != null)
            {
                activeConsole.SelectAll();
            }
        }

        protected void OnLaunchUrl(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }
}